package cube.data.util;

import cube.utils.TimeUtil;

/**
 * 速率计
 * 
 * @author abiao
 */
public class RateMeter {

    /**
     * 时延间隔
     */
    private int delay = 2000;
    private long r1, r2, rate;
    private StringBuffer sb = new StringBuffer();

    /**
     * hide me
     */
    public RateMeter() {
        this.start();
    }

    /**
     * 统计接收到的长度
     */
    public void calc(int length) {
        r2 += length;
    }

    public long getRate() {
        return rate;
    }

    /**
     * 启动速率计算
     */
    private void start() {
        startCalcRate();
        startShowRate();
    }

    /**
     * 显示速率
     */
    private void startShowRate() {
        new Thread() {
            public void run() {
                while (true) {
                    showRate();
                    TimeUtil.sleep(delay);
                }
            }
        }.start();
    }

    /**
     * 计算速率
     */
    private void startCalcRate() {
        new Thread() {
            public void run() {
                while (true) {
                    rate = r2 - r1;
                    r1 = r2;
                    TimeUtil.sleep(1000);
                }
            }
        }.start();
    }

    /**
     * 显示速率结果
     */
    private void showRate() {
        sb.setLength(0);
        long KBRate = rate / 1024;
        long MBRate = KBRate / 1024;
        long BitRate = rate * 8;
        sb.append("rate : ");
        sb.append(BitRate + " b/S ");
        sb.append(rate + " B/S ");
        sb.append(KBRate + " K/S ");
        sb.append(MBRate + " M/S ");
        System.out.println(sb.toString());
    }

    /**
     * 设置时延间隔
     */
    public RateMeter setDelay(int delay) {
        this.delay = delay;
        return this;
    }
}
